<!--
 * @Author: shenya
 * @Date: 2023-08-08 16:53:33
 * @Description: 送养协议
-->
<template>
  <el-dialog
    title="发起送养协议"
    :visible.sync="_visible"
    width="1000px"
    append-to-body
  >
    <div>签约类型：送养协议</div>
    <avue-form
      ref="addForm"
      v-model="form"
      label-width="120px"
      :option="outOption"
    >
      <template #adoptAddress>
        <el-input v-model="form.adoptAddress"></el-input>
      </template>
      <template #phone>
        <el-select
          v-model="form.phone"
          filterable
          clearable
          remote
          placeholder="请选择"
          :remote-method="remoteMethod"
          @change="changPhone"
        >
          <el-option
            v-for="item in phoneList"
            :key="item.userId"
            :label="item.phone"
            :value="item.phone"
          >
            <template>
              <div
                class="sb"
                style="padding: 0 20px"
              >
                <span>{{ item.nickname }}</span>
                <span>{{ item.phone }}</span>
              </div>
            </template>
          </el-option>
        </el-select>
      </template>
    </avue-form>
    <div
      v-for="(item, index) in list"
      :key="index"
    >
      <div class="pet-information flex align-items">
        <div class="pet-name">宠物信息</div>
        <div style="margin-left: 10px">
          <el-button
            v-if="index === 0"
            @click="insertpet"
          >
            新增宠物
          </el-button>
          <el-button
            v-else
            @click="deletePet(index)"
          >
            删除宠物
          </el-button>
        </div>
      </div>
      <div class="pet-content">
        <el-form
          ref="form"
          :model="item"
          :rules="rules"
          label-width="120px"
        >
          <el-row>
            <el-col :span="11">
              <el-form-item
                label="宠物编号："
                prop="code"
              >
                <el-select
                  v-model="item.code"
                  placeholder="请选择"
                  style="width: 100%"
                  value-key="id"
                  @change="($event) => changeId($event, index)"
                >
                  <el-option
                    v-for="v in petList"
                    :key="v.id"
                    :label="v.code"
                    :value="JSON.stringify(v)"
                  >
                    <template>
                      <div
                        class="sb"
                        style="padding: 0 20px"
                      >
                        <span>{{ v.nickName }}</span>
                        <span>{{ v.code }}</span>
                      </div>
                    </template>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item
                label="宠物昵称："
                prop="nickName"
              >
                <el-input
                  v-model="item.nickName"
                  disabled
                  placeholder="根据宠物编号自动带出"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item
                label="宠物品种："
                prop="varietyName"
              >
                <el-input
                  v-model="item.varietyName"
                  disabled
                  placeholder="根据宠物编号自动带出"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item
                label="性别："
                prop="gender"
              >
                <el-input
                  v-model="item.gender"
                  disabled
                  placeholder="根据宠物编号自动带出"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item
                label="所属爱心收容站:"
                prop="baseName"
              >
                <el-input
                  v-model="item.baseName"
                  disabled
                  placeholder="根据宠物编号自动带出"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item
                label="收容站位置："
                prop="baseAddress"
              >
                <el-input
                  v-model="item.baseAddress"
                  disabled
                  placeholder="根据宠物编号自动带出"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </div>
    <span slot="footer">
      <el-button @click="_visible = false">取 消</el-button>
      <el-button
        :loading="loading"
        type="primary"
        @click="submitForm"
      >
        确 定
      </el-button>
    </span>
  </el-dialog>
</template>
<script>
import { outOption } from '@/const/crud/pet/contractMng';
import { getPhoneList, selectPetById, addObj } from '@/api/core/agreement';
import { RESERVE_AGGREE } from '@/const/type';
export default {
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      form: {},
      outOption: outOption,
      phoneList: [],
      petList: [],
      loading: false,
      RESERVE_AGGREE,
      list: [
        {
          code: '',
          nickName: '',
          varietyName: '',
          gender: '',
          baseName: '',
          baseAddress: '',
        },
      ],
      rules: {
        code: [
          {
            required: true,
            trigger: blur,
            message: '请选择编号',
          },
        ],
      },
    };
  },
  computed: {
    _visible: {
      get() {
        return this.visible;
      },
      set(val) {
        this.$emit('update:visible', val);
      },
    },
  },
  watch: {
    _visible(val) {
      if (!val) {
        this.$refs['addForm'].resetFields();
        this.list = [
          {
            code: '',
            nickName: '',
            varietyName: '',
            gender: '',
            baseName: '',
            baseAddress: '',
          },
        ];
      }
    },
  },
  mounted() {},
  methods: {
    //新增宠物
    insertpet() {
      this.list.push({
        code: '',
        nickName: '',
        varietyName: '',
        gender: '',
        baseName: '',
        baseAddress: '',
      });
    },
    //删除宠物
    deletePet(index) {
      this.list.splice(index, 1);
    },
    changeId(val, index) {
      this.list.splice(index, 1, JSON.parse(val));
    },
    selectPetById() {
      selectPetById(this.form.userId).then((res) => {
        this.petList = res.data.data;
      });
    },
    remoteMethod(phone) {
      if (phone !== '' && phone.length > 1) {
        setTimeout(() => {
          this.getUserPhoneList({ phone });
        }, 50);
      } else {
        this.phoneList = [];
      }
    },
    changPhone(val) {
      const data = this.phoneList.find((item) => {
        return item.phone === val;
      });
      this.form.adoptName = data.name;
      this.form.adoptCard = data.idCard;
      this.form.userId = data.userId;
      this.form.nickName = data.nickname;
      this.selectPetById();
    },
    async getUserPhoneList(params) {
      this.phoneList = [];
      const res = await getPhoneList({
        ...params,
        type: '1',
        giverFlag: '1',
      });
      this.phoneList = res.data.data;
    },
    async submitForm() {
      const p1 = () => {
        return new Promise((resolve) => {
          this.$refs.addForm.validate((valid) => {
            resolve(valid);
          });
        });
      };
      const p2 = () => {
        const arr = this.$refs.form.map((el) => {
          return new Promise((resolve) => {
            el.validate((valid) => {
              resolve(valid);
            });
          });
        });
        return arr;
      };
      const res = await Promise.all([p1(), ...p2()]);
      const flag = res.every((el) => el === true);
      if (flag) {
        this.loading = true;
        const params = {
          agreementPetInfoBOList: this.list.map((v) => {
            return {
              baseId: v.baseId,
              petId: v.id,
            };
          }),
          userId: this.form.userId,
          adoptAddress: this.form.adoptAddress,
          type: RESERVE_AGGREE.PLACE_OUT_ADOPT,
        };
        addObj(params)
          .then((res) => {
            if (!res.data) return;
            this.$emit('refreshList');
            this._visible = false;
            this.loading = false;
            this.$message.success('新增成功！');
          })
          .catch((err) => {
            this.loading = false;
            throw new Error(err);
          });
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.pet-information {
  margin-top: 20px;
  position: relative;
  margin-left: 14px;
  .pet-name {
    font-size: 16px;
    &::before {
      content: '';
      position: absolute;
      width: 6px;
      height: 20px;
      background-color: red;
      left: -12px;
      border-radius: 4px;
    }
  }
}
.pet-content {
  margin-top: 20px;
  margin-left: 40px;
}
</style>
